<template>
  <div class="forgot-password-container" style="background-image: url('http://localhost:8992/user/photo/mian.png'); background-size: cover; background-position: center;">
    <div class="forgot-password-card">
      <div class="avatar-container">
        <img src="http://localhost:8992/user/photo/tou.png" alt="Avatar" class="avatar">
      </div>
      <h2 class="title">数字人模拟面试系统</h2>
      <p class="subtitle">找回您的密码</p>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="0">
        <el-form-item prop="phone">
          <el-input v-model="form.u" :prefix-icon="PhoneFilled" placeholder="请输入您的手机号" prefix-icon="el-icon-mobile-phone"></el-input>
        </el-form-item>
        <el-form-item class="flex items-center">
          <el-input v-model="form.verificationCode" placeholder="请输入验证码" style="flex: 1;"></el-input>
          <el-button @click="sendVerificationCode" :disabled="isSendingCode || codeSent" class="ml-3 py-1 px-3">
            {{ codeSent ? `已发送（${countdown}s）` : '发送验证码' }}
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="verifyCode">验证验证码</el-button>
        </el-form-item>
        <el-form-item v-if="codeVerified">
          <el-input v-model="form.passwordx"  :prefix-icon="Lock" placeholder="请输入新密码" type="password" prefix-icon="el-icon-lock"></el-input>
        </el-form-item>
        <el-form-item v-if="codeVerified">
          <el-input v-model="form.confirmPassword"  :prefix-icon="Lock" placeholder="请再次输入新密码" type="password" prefix-icon="el-icon-lock"></el-input>
        </el-form-item>
        <el-form-item v-if="codeVerified">
          <el-button type="primary" @click="resetPassword">重置密码</el-button>
        </el-form-item>
      </el-form>
      <div class="copyright">© 2025 数字人模拟面试系统 版权所有</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from "axios";
import { ChatDotRound, Bell, Message,User,Hide,Lock} from '@element-plus/icons-vue';
import router from "@/router/index.js";

// 表单引用
const formRef = ref(null);
// 表单数据
const form = ref({
  u: '',
  verificationCode: '',
  passwordx: '',
  confirmPassword: ''
});
// 表单验证规则
const rules = ref({
  u: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  passwordx: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value!== form.value.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
});

// 发送验证码状态
const isSendingCode = ref(false);
const codeSent = ref(false);
const countdown = ref(60);
let timer = null;

// 验证码验证状态
const codeVerified = ref(false);
// 存储生成的随机验证码
const generatedCode = ref('');

// 生成随机 4 位数验证码
const generateVerificationCode = () => {
  const min = 1000;
  const max = 9999;
  generatedCode.value = Math.floor(Math.random() * (max - min + 1)) + min + '';
};

// 发送验证码
const sendVerificationCode = async () => {
  try {
    // await formRef.value.validateField('phone');
    isSendingCode.value = true;
    // 生成随机验证码
    generateVerificationCode();
    codeSent.value = true;
    startCountdown();
    ElMessage.success('验证码已发送：' + generatedCode.value);
  } catch (error) {
    console.error('发送验证码出错', error);
  } finally {
    isSendingCode.value = false;
  }
};

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60;
  timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(timer);
      codeSent.value = false;
    }
  }, 1000);
};

// 验证验证码
const verifyCode = async () => {
  try {
    await formRef.value.validateField('verificationCode');
    if (form.value.verificationCode === generatedCode.value) {
      codeVerified.value = true;
      ElMessage.success('验证码验证成功');
    } else {
      ElMessage.error('验证码错误，请重新输入');
    }
  } catch (error) {
    console.error('验证验证码出错', error);
  }
};

// 重置密码
const resetPassword = async () => {
  axios({
    url: "/api/user/user/upd",
    method: "get",
    params: form.value
  }).then((rew) => {
    if (rew.data != null) {
      ElMessage.success("重置密码成功");
      router.push("/")
    } else {
      ElMessage.error("密码重置失败");
    }
  });
};

// 清理定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});
</script>

<style scoped>
.forgot-password-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
.forgot-password-card {
  background-color: rgba(255, 255, 255, 0.8);
  padding: 40px 100px;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}
.avatar-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}
.avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
}
.title {
  text-align: center;
  margin-bottom: 10px;
}
.subtitle {
  text-align: center;
  color: #666;
  margin-bottom: 20px;
}
.copyright {
  text-align: center;
  margin-top: 20px;
  color: #999;
  font-size: 12px;
}
.flex.items-center {
  display: flex;
  align-items: center;
}
.ml-3 {
  margin-left: 12px;
}
.py-1 {
  padding-top: 4px;
  padding-bottom: 4px;
}
.px-3 {
  padding-left: 12px;
  padding-right: 12px;
}
</style>